let weakMap: WeakMap<File | Blob, Promise<string>> | undefined;
// 做个对象弱缓存
if (window.WeakMap) {
  weakMap = new WeakMap();
}
export function fileToBase64(file: File | Blob) {
  if (weakMap) {
    let result = weakMap.get(file);
    if (result) {
      return result;
    }
  }

  let promise = new Promise<string>((resolve) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      const base64 = reader.result;
      if (typeof base64 === 'string') {
        resolve(base64);
      } else {
        resolve('');
      }
    };
  });
  weakMap?.set(file, promise);

  return promise;
}

/**
 *
 *
 * @export
 * @param {string} videoStr
 * @param {{ width: number, height: number }} itemRenderSize
 * @returns {Promise<string>}
 * @description 根据视频url获取视频第一帧图片
 */
export function getVideoCoverImage(
  videoStr: string,
  itemRenderSize: { width: number; height: number },
): Promise<string> {
  return new Promise((resolve, reject) => {
    let videoss = document.createElement('video');
    let canvas = document.createElement('canvas');
    videoss.src = videoStr;
    videoss.load(); //加载视频
    videoss.setAttribute('crossOrigin', 'anonymous'); //处理跨域
    videoss.currentTime = 1; // 第x帧
    videoss.volume = 0;
    videoss.addEventListener('loadedmetadata', () => {
      videoss.addEventListener('canplay', () => {
        setTimeout(() => {
          const context = canvas.getContext('2d');
          const { width, height } = itemRenderSize;
          canvas.width = width;
          canvas.height = height;
          // 绘制视频第一帧到canvas
          context!.drawImage(videoss, 0, 0, canvas.width, canvas.height);
          const dataURL = canvas.toDataURL('image/jpeg');
          resolve(dataURL);
          videoss.pause(); //暂停
          (videoss as any) = null;
          (canvas as any) = null;
        }, 100);
      });
      videoss.play();
    });
  });
}
